package com.gmail.hy87cn.hellohi.server;

import com.gmail.hy87cn.hellohi.client.HiService;
import com.gmail.hy87cn.hellohi.shared.ERoomState;
import com.gmail.hy87cn.hellohi.shared.HiMessage;
import com.gmail.hy87cn.hellohi.shared.HiRoom;
import com.gmail.hy87cn.hellohi.shared.HiUpdateException;
import com.gmail.hy87cn.hellohi.shared.HiUser;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class HiServiceImpl extends RemoteServiceServlet implements HiService {

	private HiUserManager userMgr = HiUserManager.sGetInstance();

	@Override
	public int getToken() {
		return userMgr.createUser();
	}

	@Override
	public HiMessage[] updateMessages(int token, int lastIndex)
			throws HiUpdateException {
		HiUserPackage user = userMgr.getUser(token);
		user.setAlive();

		HiRoomPackage room = user.getRoomPackage();
		if (room != null && room.getRoom().getState() == ERoomState.Locked) {
			for (HiUser stranger : room.getRoom().getUserList()) {
				if (!userMgr.getUser(stranger.getId()).isAlive()) {
					releaseToken(stranger.getId());
				}
			}
			return room.getMessages(token, lastIndex);
		} else {
			throw new HiUpdateException();
		}
	}

	@Override
	public void sendMessage(int token, String input) {
		HiMessage message = new HiMessage(token, input);
		userMgr.getUser(token).getRoomPackage().addMessage(message);
	}

	@Override
	public void connect(int token, String facebookId) {
		userMgr.connect(token, facebookId);
	}

	@Override
	public void disconnect(int token) {
		userMgr.disconnect(token);
	}

	@Override
	public void releaseToken(int token) {
		userMgr.disconnect(token);
		userMgr.removeUser(token);
	}

	@Override
	public HiRoom getRoom(int token) {
		HiUserPackage userPackage = userMgr.getUser(token);
		if (userPackage != null) {
			userPackage.setAlive();
			HiRoomPackage roomPackage = userPackage.getRoomPackage();
			if (roomPackage != null) {
				return roomPackage.getRoom();
			} else {
				return null;
			}
		}
		return null;
	}
}
